package cn.good.yan.basics.t3.service;

import cn.good.yan.basics.t3.mapper.ProviderMapper;
import cn.good.yan.basics.t3.pojo.Provider;
import cn.good.yan.basics.t3.utils.RedisC;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Redis 操作案例
 * @author shengren.yan
 * @create 2022-11-24
 */
@Service
public class ProviderService {

    // Redis工具类
    @Autowired(required = false)
    private RedisC redisClient;

    @Autowired(required = false)
    ProviderMapper providerMapper;

    public Provider getProviderByPid(Integer pid){
        // 1.先查询一下缓存中是否有数据
        Object obj = redisClient.get("provider" + pid);
        if(obj != null) {
//            Provider p = JSON.parseObject(JSON.toJSONString(obj), Provider.class); // json 获取 ，都可以实现
            Provider p = new ObjectMapper().convertValue(obj, Provider.class);  // ObjectMapper 获取 ，都可以实现
            return p;
//            return (Provider) obj;  (强转失败)
        }
        // 2.如果缓存中没有,则查数据库,然后添加到缓存中
//        Provider provider = providerMapper.getProviderByPid(pid);
        Provider provider = new Provider();
        provider.setPid(3);
        provider.setProviderCode("北京");
        provider.setFax("ssss1");
        redisClient.set(pid, provider);
        return provider;
    }

    public Integer updateProvider(Provider provider) {
        // 修改
//        int size = providerMapper.updateProvider(provider);
        int size = 1;
        if(size > 0) {
            // 更新缓存数据
            redisClient.set("provider" + provider.getPid(), provider);
        }
        return size;
    }

    public Integer addProvider(Provider provider){
        // 新增
//        int size = providerMapper.addProvider(provider);
        int size = 1;
        if(size > 0) {
            redisClient.set("provider" + provider.getPid(), provider);
        }
        return size;
    }

    public Integer deleteProviderByPid(Integer pid) {
//        int size = providerMapper.deleteProviderByPid( pid); // 删除数据库
        int size = 1;
        if(size > 0) {
            // 清除key=pid缓存
            redisClient.del("provider" + pid);
        }
        return size;
    }

}
